package com.yjhb.android.sbz.activity;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yjhb.android.sbz.Conf;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.entity.WxPayParam;
import com.yjhb.android.sbz.mvp.recharge.RechargePresenter;
import com.yjhb.android.sbz.mvp.recharge.RechargeView;
import com.yjhb.android.sbz.tool.DataSaveTool;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.tool.LoadingDialogTool;
import com.yjhb.android.sbz.tool.PayTool;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.tool.wx.WxTool;
import com.yjhb.android.sbz.v2.dialog.BondMoneyDialog;
import com.jojo.android.zxlib.interfaces.Callback;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.view.dialog.ILoading;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建者 zx
 * 创建时间 2020/12/2 17:10
 */
public class RechargeActivity extends BaseActivity<RechargePresenter> implements RechargeView {
    private final String TAG = "RechargeActivity";

    public static final int RESULT_RECHARGE_SUCCESS = 10086;

    View selectedType;


    @BindView(R.id.money_et)
    EditText money_et;
    @BindView(R.id.title_tv)
    TextView title_tv;
    @BindView(R.id.tips_tv)
    TextView tips_tv;
    @BindView(R.id.zfb_layout)
    LinearLayout zfb_layout;
    @BindView(R.id.wx_layout)
    LinearLayout wx_layout;

    ILoading loadingDialog;
    private String orderId;
    private Integer target;
    private boolean isBack;

    @Override
    protected RechargePresenter initPresenter() {
        return new RechargePresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recharge;
    }

    //target:订单资金目标：2、充值金；3、保证金；4、VIP充值
    @Override
    protected void initUI() {
        loadingDialog = LoadingDialogTool.createDialog(this);
        selectedType = rootView.findViewWithTag("zfb");
        target = getIntent().getIntExtra("target", 2);
        switch (target) {
            case 2:
                title_tv.setText("金额充值");
                tips_tv.setText("充值提示：\n" +
                        "1、充值金额提现将收取一定的手续费，请适当充值。\n" +
                        "2、24小时内到账。\n" +
                        "3、如果查出套现洗钱嫌疑，将延迟5-7个工作日提现，情节恶劣者将进行封号处罚和充值限制！");
                break;
            case 3:
                title_tv.setText("保证金充值");
                tips_tv.setText("");
                money_et.setHint("请输入充值金额(100元起)");
                if (DataSaveTool.isShowBondMoney()) {
                    BondMoneyDialog bondMoneyDialog = new BondMoneyDialog(this);
                    bondMoneyDialog.show();
                }
                break;
            case 4:
                title_tv.setText("会员充值");
                tips_tv.setText("");
                break;
        }
        String m = getIntent().getStringExtra("money");
        if (!TextUtils.isEmpty(m)) {
            money_et.setText(m);
            money_et.setEnabled(false);
        }
        isBack = getIntent().getBooleanExtra("isBack", false);
        onSelectedType(selectedType);
//        tips_tv.setText(getTips());
    }

    @Override
    protected void initData() {
        int type = -1;
        switch (target) {
            case 2:
                type = 5;
                break;
            case 3:
                type = 6;
                break;
            case 4:
                type = 4;
                break;
        }
        if (type == -1) return;
        presenter.specifyConfig(type);
    }

    @Override
    protected void regEvent() {

    }


    @OnClick(R.id.back)
    public void back() {
        finish();
    }

    @OnClick({R.id.wx_layout, R.id.zfb_layout})
    public void onSelectedType(View view) {
        if (selectedType != null) {
            selectedType.setSelected(false);
        }
        selectedType = view;
        selectedType.setSelected(true);
    }

    @OnClick(R.id.recharge_tv)
    public void recharge_tv() {
        if (Tool.isEditEmpty(money_et)) {
            ZxToast.showBottomToastLight("请输入充值金额。");
            return;
        }
        try {
            String type = (String) selectedType.getTag();
            if (type.equals("zfb")) {
                presenter.pay(1, new BigDecimal(money_et.getText().toString()), target);
            } else if (type.equals("wx")) {
                presenter.pay(2, new BigDecimal(money_et.getText().toString()), target);
            }
        } catch (Exception e) {
            ZxToast.showBottomToastLight("出现了异常~~");
        }

    }

    @OnClick(R.id.history_tv)
    public void history_tv() {
        ZxActivityTool.skipActivity(this, RechargeHistoryActivity.class);
    }


    @Override
    public void onWait() {
        loadingDialog.show();
    }

    @Override
    public void onSuccess(String data) {

    }

    @Override
    public void onSuccessWx(WxPayParam payParam) {
        loadingDialog.cancel();
        PayTool.payWechat(this, payParam.getSign(),
                payParam.getPrepayId(),
                payParam.getNonceStr(),
                "" + payParam.getTimestamp());
    }

    @Override
    public void onSuccessAli(String data) {
        loadingDialog.cancel();
        if (!TextUtils.isEmpty(data)) {
            String biz_content = "";
            String[] splits = data.split("&");
            for (int i = 0; i < splits.length; i++) {
                if (splits[i].contains("biz_content")) {
                    biz_content = splits[i];
                }
            }
            String[] biz = biz_content.split("%22%2C%22");
            if (biz != null) {
                for (int i = 0; i < biz.length; i++) {
                    if (biz[i].contains("out_trade_no%22%3A%22")) {
                        orderId = biz[i].replaceAll("out_trade_no%22%3A%22", "");
                    }
                }
            }
        }
        PayTool.AliPay(this, data, new Callback<Map<String, String>>() {
            @Override
            public void callback(Map<String, String> stringStringMap) {
                try {
                    if (stringStringMap.toString().contains("resultStatus=6001")) {
                        presenter.aliCancelOrder(orderId);
                        ZxToast.showINFOCenterToast("已取消");
                        return;
                    }
                    if (stringStringMap.toString().contains("\"msg\":\"Success\"")) {
                        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
                        ZxToast.showSuccessCenterToast("充值成功！");
                        if (isBack) {
                            setResult(RESULT_RECHARGE_SUCCESS);
                            finish();
                        }
                    }
                } catch (Exception e) {
                    ZxLogTool.err(e);
                }

            }
        });
    }

    @Override
    public void onDisplay(boolean alipay, boolean wechat) {
        zfb_layout.setVisibility(alipay?View.VISIBLE:View.GONE);
        wx_layout.setVisibility(wechat?View.VISIBLE:View.GONE);
    }

    @Override
    public void onEventMsg(EventMsg msg) {
        super.onEventMsg(msg);
        if (msg.msg == EventMsg.USER_WX_RESULT) {
            BaseResp resp = (BaseResp) msg.object;
            if (resp != null) {
                if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
                    EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
                    ZxToast.showSuccessCenterToast("充值成功！");
                    if (isBack) {
                        setResult(RESULT_RECHARGE_SUCCESS);
                        finish();
                    }
                } else if (resp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
                    ZxToast.showINFOCenterToast("已取消");
                }
            }
        }
    }

    @Override
    public void onFailure(int code, String msg) {
        loadingDialog.cancel();
        ZxToast.showFAILCenterToast(msg);
    }

    @Override
    public void onAliCancel() {

    }
}
